<script setup>
import {ref, reactive, watch, computed, toRefs} from 'vue';
import {
  getScreeningTopic,
  updateScreeningTopic
} from "@/api/system/ScreeningTopic.js";
import {useToggle} from 'vue-hooks-plus'

// 动态切换状态
const [flag, {toggle, setLeft, setRight}] = useToggle()
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    choice: null,
    choiceValue: null,
    showorder: null
  },
  rules: {}
});
const items = ref([]);
const multiple = ref(true);
const total = ref(0);
const loading = ref(false);
const choiceList = ref([]);
const {proxy} = getCurrentInstance();
const {queryParams, form, rules} = toRefs(data);
// 选项表单
const choiceForm = ref({})
const props = defineProps({
  title: {
    type: String,
    default: '提示',
  },
  topicId: {
    type: Number,
    default: 0
  },
  visible: {
    type: Boolean,
    default: false,
  },
  onClose: {
    type: Function,
    required: true,
  },
});

const {topicId} = toRefs(props);
let previousId = null;

// 监听父组件给的id 变化
watch(topicId, (newId) => {
  if (newId !== previousId) {
    getList(newId);
    previousId = newId; // 更新之前的 ID
  }
}, {immediate: true});


const isVisible = computed(() => props.visible);

// 关闭弹窗
const closeDialog = () => {
  props.onClose();
};

// 题目列表
function getList(topicId) {
  loading.value = true;
  getScreeningTopic(topicId).then(response => {
    form.value = response.data;
    choiceList.value = response.data.screeningTopicChoiceList;
    total.value = response.data.screeningTopicChoiceList.length;
    loading.value = false;
  });
}

function handleAdd() {
  setRight()
}

// 新增或修改
function handleUpdateChoices() {
  if (choiceForm.value.id !== undefined) {
    // 点击确定 然后把 choiceForm 更新
    choiceList.value.forEach(item => {
      if (item.id === choiceForm.value.id) {
        item.choice = choiceForm.value.choice
        item.choiceValue = choiceForm.value.choiceValue
        item.showorder = choiceForm.value.showorder
      }
    })
    // 修改
    updateScreeningTopic({...form.value, screeningTopicChoiceList: choiceList.value})
        .then(res => {
          proxy.$modal.msgSuccess("修改选项成功~")
          setLeft()
          getList(previousId)
          reset()
        })
        .catch(err => {
          proxy.$modal.msgError(err)
          getList(previousId)
          reset()
        })
  } else {
    choiceList.value.push(choiceForm.value)
    // 修改
    updateScreeningTopic({...form.value, screeningTopicChoiceList: choiceList.value})
        .then(res => {
          proxy.$modal.msgSuccess("添加选项成功~")
          setLeft()
          getList(previousId)
          reset()
        })
        .catch(err => {
          proxy.$modal.msgError(err)
          choiceList.value.pop()
          getList(previousId)
          reset()
        })
  }
}

// 修改按钮操作
function handleUpdate(row) {
  setRight()
  // previousId 就是该行的对象
  getScreeningTopic(previousId).then(res => {
    choiceForm.value = res.data.screeningTopicChoiceList.find(item => item.id === row.id)
  })
}

// 删除选项
function handleDelete() {
  const _choiceList = choiceList.value
  proxy.$modal.confirm('是否确认删除所选中的题目选项？').then(function () {
    items.value.forEach(item => {
      _choiceList.pop(item)
    })
    const newData = {
      id: topicId.value,
      // 不包含的留下
      screeningTopicChoiceList: _choiceList
    };
    return updateScreeningTopic(newData);
  }).then(() => {
    getList(previousId);
    proxy.$modal.msgSuccess("删除成功");
  })
}

function beforeClose() {
  setLeft();
}

function reset() {
  choiceForm.value = {}
  choiceList.value = []
}

function handleSelectionChange(selection) {
  items.value = selection;
  multiple.value = !selection.length >= 1;
}


</script>

<template>
  <div>
    <!--    选项列表-->
    <el-dialog
        v-model="isVisible"
        :title="title"
        width="870px">
      <el-row>
        <el-button
            type="text"
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:choice:remove']"
        >新增选项
        </el-button>
        <el-button
            type="text"
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:choice:remove']"
        >删除选项
        </el-button>
      </el-row>
      <el-table v-loading="loading" :data="choiceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="id" align="center" prop="id"/>
        <el-table-column label="选项" align="center" prop="choice"/>
        <el-table-column label="选项对应值" align="center" prop="choiceValue"/>
        <el-table-column label="显示顺序" align="center" prop="showorder"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:choice:edit']">修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="closeDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>


    <!--    修改选项的弹窗-->
    <el-dialog
        v-model="flag"
        title="修改选项"
        width="500" :before-close="beforeClose">
      <el-form :model="choiceForm" class="demo-form-inline">
        <el-form-item label="选项名">
          <el-input v-model="choiceForm.choice" placeholder="选项" clearable/>
        </el-form-item>
        <el-form-item label="选项对应值">
          <el-input v-model="choiceForm.choiceValue" placeholder="选项对应值" clearable/>
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input v-model="choiceForm.showorder" placeholder="显示顺序" clearable/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="setLeft">取消</el-button>
          <el-button type="primary" @click="handleUpdateChoices">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
